package top.hcode.hoj.dao.course;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.sagacity.sqltoy.model.Page;
import org.springframework.stereotype.Service;
import top.hcode.hoj.dao.BaseDao;
import top.hcode.hoj.mapper.QuestionMapper;
import top.hcode.hoj.pojo.dto.QueryQuestionDTO;
import top.hcode.hoj.pojo.entity.course.Question;
import top.hcode.hoj.pojo.vo.QuestionVO;
import top.hcode.hoj.utils.PageUtil;

import java.util.List;

/**
 * @author orangej
 * @since 2024/12/18
 */
@Service
public class QuestionDao extends BaseDao<QuestionMapper, Question> {

    public void loadChildren(Question question) {
        if (question == null || question.getId() == null || !BooleanUtil.isTrue(question.getHasChildren())) {
            return;
        }

        List<Question> children = this.list(new QueryWrapper<Question>().eq("parent_id", question.getId()));
        question.setChildren(children);
    }

    public QuestionVO fetchQuestionVO(Long id) {
        QuestionVO vo = lazyDao.selectOne(QuestionVO.class, "queryQuestionVO", NutMap.NEW().addv("id", id));
        linkLoader.loadTags(vo);
        loadChildren(vo);
        return vo;
    }

    public List<QuestionVO> queryQuestionVO(List<Long> ids) {
        List<QuestionVO> voList = lazyDao.selectList(QuestionVO.class, "queryQuestionVO", NutMap.NEW().addv("ids", ids));
        linkLoader.loadTags(voList);
        voList.forEach(this::loadChildren);
        return voList;
    }

    public IPage<QuestionVO> queryQuestionVOPage(QueryQuestionDTO dto) {
        Page<QuestionVO> pager = new Page<>(dto.getLimit(), dto.getCurrentPage());
        pager = lazyDao.findPageBySql(pager, "queryQuestionVO", Lang.obj2map(dto), QuestionVO.class);

        List<QuestionVO> records = pager.getRows();
        linkLoader.loadTags(records);
        records.forEach(this::loadChildren);

        return PageUtil.toMybatis(pager);
    }


}
